package com.xsprite.managesys.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class AuthorityFilter implements Filter {

	/**
	 * 需要排除的页面
	 */
	private String excludedPages;
	private String[] excludedPageArray;

	public void destroy() {

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpServletResponse servletResponse = (HttpServletResponse) response;
		HttpSession session = servletRequest.getSession();
		String userid = (String) session.getAttribute("userid");
		String path = servletRequest.getRequestURI();

		boolean isExcludedPage = false;
		for (String page : excludedPageArray) {// 判断是否在过滤url之外
			if (path.contains(page)) {
				isExcludedPage = true;
				break;
			}
		}

//		System.out.println(excludedPages);
		if(isExcludedPage){
			chain.doFilter(servletRequest, servletResponse);
			return;
		} else if (path.indexOf("/index.jsp") > -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		} else if (path.indexOf("/helloworld.jsp") > -1){
			chain.doFilter(servletRequest, servletResponse);
			return;
		}

		if (userid == null || "".equals(userid)) {
			// 跳转到登陆页面
			servletResponse.sendRedirect("/ZZManageSys/index.jsp");
		} else {
//			if(isServlet(path)){
//				
//			}
			// 已经登陆,继续此次请求
			chain.doFilter(request, response);
			return;
		}
		// chain.doFilter(request, response);
	}
	
	private boolean isServlet(String path){
		if(path.indexOf("Servlet") == -1){
			return true;
		}
		return false;
	}
	
	public void init(FilterConfig cofnig) throws ServletException {
		excludedPages = cofnig.getInitParameter("excludedPages");
		excludedPageArray = excludedPages.split(",");
	}
}
